package nckd.wnqjt.tmc.tda.plugin.form;

import java.math.BigDecimal;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.*;

import com.alibaba.fastjson.JSON;
import kd.bos.algo.*;
import kd.bos.algo.input.CollectionInput;
import kd.bos.dataentity.entity.DynamicObject;
import kd.bos.dataentity.entity.DynamicObjectCollection;
import kd.bos.dataentity.entity.LocaleString;
import kd.bos.entity.qing.*;
import kd.bos.entity.qing.Field;
import kd.bos.form.IPageCache;
import kd.bos.form.plugin.AbstractFormPlugin;
import kd.bos.orm.query.QCP;
import kd.bos.orm.query.QFilter;
import kd.bos.servicehelper.BusinessDataServiceHelper;
import kd.bos.servicehelper.QueryServiceHelper;
import kd.bos.servicehelper.operation.SaveServiceHelper;

/**
 * @author husheng
 * @date 2024-11-04 11:55
 * @description 动态表单插件      担保人分布
 */
public class GuaranteeorgQingDataProvider extends AbstractFormPlugin implements IQingDataProvider {
    /**
     * 定义轻分析表头
     */
    @Override
    public QingMeta getMeta(String s) {
        String entityKey = "gm_guaranteecontract";
        QingMeta meta = new QingMeta();
        EntryEntity entity = new EntryEntity();
        entity.setKey(entityKey);
        entity.setName(new LocaleString("PK"));
        entity.setPkFieldName("id");
        meta.addEntryEntity(entity);

        Field column = new Field();
        column.setEntity(entityKey);//字段所属实体key	否
        column.setKey("id");// 字段名(唯一标识)	是
        column.setFieldType(QingFieldType.Int.toNumber()); //数据类型	是
        column.setName(new LocaleString("id")); //字段别名	是
        meta.addColumn(column);

        column = new Field();
        column.setEntity(entityKey);
        column.setKey("orgName");
        column.setFieldType(QingFieldType.String.toNumber());
        column.setName(new LocaleString("资金组织"));
        meta.addColumn(column);

        column = new Field();
        column.setEntity(entityKey);
        column.setKey("bizdate");
        column.setFieldType(QingFieldType.Date.toNumber());
        column.setName(new LocaleString("日期"));
        meta.addColumn(column);

        column = new Field();
        column.setEntity(entityKey);
        column.setKey("guaranteetype");
        column.setFieldType(QingFieldType.String.toNumber());
        column.setName(new LocaleString("担保人类型"));
        meta.addColumn(column);

        column = new Field();
        column.setEntity(entityKey);
        column.setKey("amount");
        column.setFieldType(QingFieldType.Number.toNumber());
        column.setName(new LocaleString("总额"));
        meta.addColumn(column);

        column = new Field();
        column.setEntity(entityKey);
        column.setKey("seq");
        column.setFieldType(QingFieldType.Int.toNumber());
        column.setName(new LocaleString("seq"));
        meta.addColumn(column);

        return meta;
    }

    /**
     * 获取轻分析数据，通过拿到过滤条件可以重新定义取数逻辑
     */
    @Override
    public QingData getData(String s, int i, int i1) {
        //拿过滤条件，进行取数
        String qFilter = getPageCache().get("qFilter");
        if (qFilter != null) {
            //通过此方法拿到过滤参数
            Map<String, Object> filterParam = (Map) JSON.parseObject(qFilter, Map.class);
        }

        // 查询担保合同
        String guaranteecontractSql = "id,billno,org.id orgId,org.name orgName,org.number orgNumber,bizdate," +
                "entry_guaranteeorg.a_guaranteeorg,entry_guaranteeorg.a_gratio";
        QFilter filter1 = new QFilter("billstatus", QCP.equals, "C");
        DataSet gmGuaranteecontract = QueryServiceHelper.queryDataSet(this.getClass().getName(), "gm_guaranteecontract", guaranteecontractSql, filter1.toArray(), null);

        /**
         * 0 江西省建材集团有限公司
         * C01	万年青水泥股份本部
         * C010301	南方万年青本部
         * C0108	德安万年青本部
         */
        DynamicObject dynamicObject1 = BusinessDataServiceHelper.loadSingle("bos_org", new QFilter[]{new QFilter("number", QCP.equals, "0")});
        DynamicObject dynamicObject2 = BusinessDataServiceHelper.loadSingle("bos_org", new QFilter[]{new QFilter("number", QCP.equals, "C01")});
        DynamicObject dynamicObject3 = BusinessDataServiceHelper.loadSingle("bos_org", new QFilter[]{new QFilter("number", QCP.equals, "C010301")});
        DynamicObject dynamicObject4 = BusinessDataServiceHelper.loadSingle("bos_org", new QFilter[]{new QFilter("number", QCP.equals, "C0108")});

        // 根据担保人类型分类
        DataSet guaranteecontract1 = gmGuaranteecontract.copy().filter("entry_guaranteeorg.a_guaranteeorg = " + dynamicObject1.getLong("id"));
        DataSet guaranteecontract2 = gmGuaranteecontract.copy().filter("entry_guaranteeorg.a_guaranteeorg = " + dynamicObject2.getLong("id"));
        DataSet guaranteecontract3 = gmGuaranteecontract.copy().filter("entry_guaranteeorg.a_guaranteeorg = " + dynamicObject3.getLong("id"));
        DataSet guaranteecontract4 = gmGuaranteecontract.copy().filter("entry_guaranteeorg.a_guaranteeorg = " + dynamicObject4.getLong("id"));
        DataSet guaranteecontract5 = gmGuaranteecontract.copy().filter("entry_guaranteeorg.a_guaranteeorg not in (" + dynamicObject1.getLong("id") + "," + dynamicObject2.getLong("id") + "," + dynamicObject3.getLong("id") + "," + dynamicObject4.getLong("id") + ")");

        // 担保占用-担保中   担保比例为0是已解除，剩余债务金额为0是已结清，否则为担保中
        // 担保债务的债务单据类型是开票登记 cdm_payablebill，剩余债务金额不会更新值，因此票据状态是解付、拆分的开票需动态的将剩余债务金额赋值为0
        //kd.tmc.gm.formplugin.contract.GuaranteeContractUseEdit.loadGuaranteeContractUse
        QFilter gQF = new QFilter("billstatus", QCP.equals, "C")
                .and("gsrcbilltype", QCP.not_equals, "cfm_creditlimit")
                .and("gratio", QCP.not_equals, BigDecimal.ZERO)
                .and("gdebtbalance", QCP.not_equals, BigDecimal.ZERO)
                .and("gsrcbilltype", QCP.equals, "cdm_payablebill");
        DataSet gcUseBills1 = QueryServiceHelper.queryDataSet(this.getClass().getName(), "gm_guaranteeuse", "id,gcontract.id gcontractId,gdebtbalance,gsrcbillid", gQF.toArray(), null);
        QFilter filter = new QFilter("rptype", QCP.equals, "paybill")
                .and("draftbillstatus", QCP.not_in, new String[]{"payoffed", "splited"})
                .and("billstatus", QCP.equals, "C");
        DataSet cdmPayablebill = QueryServiceHelper.queryDataSet(this.getClass().getName(), "cdm_payablebill", "id", filter.toArray(), null);
        gcUseBills1 = gcUseBills1.join(cdmPayablebill).on("gsrcbillid", "id").select(gcUseBills1.getRowMeta().getFieldNames()).finish();

        QFilter gQF2 = new QFilter("billstatus", QCP.equals, "C")
                .and("gsrcbilltype", QCP.not_equals, "cfm_creditlimit")
                .and("gratio", QCP.not_equals, BigDecimal.ZERO)
                .and("gdebtbalance", QCP.not_equals, BigDecimal.ZERO)
                .and("gsrcbilltype", QCP.not_equals, "cdm_payablebill");
        DataSet gcUseBills2 = QueryServiceHelper.queryDataSet(this.getClass().getName(), "gm_guaranteeuse", "id,gcontract.id gcontractId,gdebtbalance,gsrcbillid", gQF2.toArray(), null);

        DataSet gcUseBills = gcUseBills1.union(gcUseBills2);
        DataSet finish = gcUseBills.groupBy(new String[]{"gcontractId"}).sum("gdebtbalance").finish();

        DataSet finish1 = guaranteecontract1.join(finish.copy()).on("id", "gcontractId").select(gmGuaranteecontract.getRowMeta().getFieldNames(), new String[]{"gdebtbalance"}).finish();
        DataSet finish2 = guaranteecontract2.join(finish.copy()).on("id", "gcontractId").select(gmGuaranteecontract.getRowMeta().getFieldNames(), new String[]{"gdebtbalance"}).finish();
        DataSet finish3 = guaranteecontract3.join(finish.copy()).on("id", "gcontractId").select(gmGuaranteecontract.getRowMeta().getFieldNames(), new String[]{"gdebtbalance"}).finish();
        DataSet finish4 = guaranteecontract4.join(finish.copy()).on("id", "gcontractId").select(gmGuaranteecontract.getRowMeta().getFieldNames(), new String[]{"gdebtbalance"}).finish();
        DataSet finish5 = guaranteecontract5.join(finish.copy()).on("id", "gcontractId").select(gmGuaranteecontract.getRowMeta().getFieldNames(), new String[]{"gdebtbalance"}).finish();

        DataSet dataSet1 = finish1.select(new String[]{"id", "billno", "orgName", "bizdate", "(entry_guaranteeorg.a_gratio * gdebtbalance / 100) amount", "'建材集团' as guaranteetype", "1 as seq"});
        DataSet dataSet2 = finish2.select(new String[]{"id", "billno", "orgName", "bizdate", "(entry_guaranteeorg.a_gratio * gdebtbalance / 100) amount", "'股份公司' as guaranteetype", "2 as seq"});
        DataSet dataSet3 = finish3.select(new String[]{"id", "billno", "orgName", "bizdate", "(entry_guaranteeorg.a_gratio * gdebtbalance / 100) amount", "'南方万年青' as guaranteetype", "3 as seq"});
        DataSet dataSet4 = finish4.select(new String[]{"id", "billno", "orgName", "bizdate", "(entry_guaranteeorg.a_gratio * gdebtbalance / 100) amount", "'德安万年青' as guaranteetype", "4 as seq"});
        DataSet dataSet5 = finish5.select(new String[]{"id", "billno", "orgName", "bizdate", "(entry_guaranteeorg.a_gratio * gdebtbalance / 100) amount", "'其他' as guaranteetype", "5 as seq"});

        dataSet1 = this.dataSetDefaultValue(dataSet1, "建材集团", 1);
        dataSet2 = this.dataSetDefaultValue(dataSet2, "股份公司", 2);
        dataSet3 = this.dataSetDefaultValue(dataSet3, "南方万年青", 3);
        dataSet4 = this.dataSetDefaultValue(dataSet4, "德安万年青", 4);
        dataSet5 = this.dataSetDefaultValue(dataSet5, "其他", 5);

        DataSet dataSet = dataSet1.union(dataSet2, dataSet3, dataSet4, dataSet5);

        DynamicObject test = BusinessDataServiceHelper.newDynamicObject("nckd_testdocuments");
        test.set("billno", "test-guarantee5-" + new SimpleDateFormat("yyyyMMddHHmm").format(new Date()));
        test.set("billstatus", "A");
        DynamicObjectCollection entryentity = test.getDynamicObjectCollection("entryentity");
        //打印单据
        DataSet recCopy = dataSet.copy();
        while (recCopy.hasNext()) {
            DynamicObject entry = entryentity.addNew();
            Row row = recCopy.next();
            entry.set("nckd_name", "担保人分布");
            entry.set("nckd_number", row.get("billno"));
            entry.set("nckd_amount", row.get("amount"));
        }
        SaveServiceHelper.save(new DynamicObject[]{test});

        QingData data = null;
        if (i < 200) {
            data = new QingData();
            Map<String, Integer> dataindex = new HashMap<>();
            dataindex.put("id", 0);
            dataindex.put("orgName", 1);
            dataindex.put("bizdate", 2);
            dataindex.put("guaranteetype", 3);
            dataindex.put("amount", 4);
            dataindex.put("seq", 5);
            data.setDataindex(dataindex);

            List<Object[]> rows = new ArrayList<>();
            while (dataSet.hasNext()) {
                Row row = dataSet.next();
                Object[] obj = new Object[6];
                obj[0] = row.getLong("id");
                obj[1] = row.getString("orgName");
                if (row.get("bizdate") != null) {
                    Timestamp timestamp = (Timestamp) row.get("bizdate");
                    long time = timestamp.getTime();
                    obj[2] = time;
                } else {
                    obj[2] = null;
                }
                obj[3] = row.getString("guaranteetype");
                obj[4] = row.getBigDecimal("amount");
                obj[5] = row.getLong("seq");
                rows.add(obj);
            }
            data.setRows(rows);
        }

        return data;
    }

    private DataSet dataSetDefaultValue(DataSet dataSet, String type, Integer seq) {
        if (dataSet.isEmpty()) {
            // 创建一个空的DataSet
            Collection<Object[]> coll = new ArrayList<>();
            Object[] objects = {null, null, null, null, 0, type, seq};
            coll.add(objects);
            String[] fields = new String[]{"id", "billno", "orgName", "bizdate", "amount", "guaranteetype", "seq"};
            DataType[] dataTypes = new DataType[]{DataType.LongType, DataType.StringType, DataType.StringType, DataType.DateType, DataType.BigDecimalType, DataType.StringType, DataType.IntegerType};
            RowMeta rowMeta = RowMetaFactory.createRowMeta(fields, dataTypes);
            CollectionInput inputs = new CollectionInput(rowMeta, coll);
            dataSet = Algo.create(this.getClass().getName()).createDataSet(inputs);
        }

        return dataSet;
    }

    @Override
    public void setFilterParameter(String filterParameter) {
        IPageCache pageCache = getPageCache();
        pageCache.put("qFilter", filterParameter);
    }

    @Override
    public String getFilterParameter() {
        return getPageCache().get("qFilter");
    }

    private Date getCurrentDate() {
        Calendar cal = new GregorianCalendar();
//        cal.set(11, 0);
//        cal.set(12, 0);
//        cal.set(13, 0);
//        cal.set(14, 0);
        return cal.getTime();
    }
}
